/*
 * File:    Foreach.java
 * Created: 25-Feb-2009
 * Version: $Id$
 *
 * COPYRIGHT (C) 2009, Bitgate Mobile, LLC.  All Rights Reserved.
 *
 * software@bitgatemobile.com
 */

package com.webplasm.render.tags.u;

import static com.bitgate.util.debug.Debug.debug;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import com.webplasm.context.RenderContext;
import com.webplasm.render.engine.RenderException;
import com.webplasm.render.tags.TagInterface;
import com.webplasm.render.tags.WrappedNode;
import com.webplasm.store.VariableStoreInterface;
import com.webplasm.store.VariableContainer.VariableType;

/**
 * Provides an iterative way to walk through variables that have multiple values stored in an array, a hash, or in
 * SQL result sets.
 * 
 * @author kenji
 * @since Webplasm 1.0
 */
public class Foreach extends WrappedNode implements TagInterface {
	private static final String DESCRIPTION = "Provides ability to iterate through values in hashes, SQL queries, and arrays.";

	public String getNamespace() {
		return "u";
	}
	
	public List<String> getAttributes() {
		return Arrays.asList("var", "dest");
	}
	
	public List<String> getManagedNodes() {
		return null;
	}

	public String getDescription() {
		return DESCRIPTION;
	}

	@SuppressWarnings("unchecked")
	@Override
	public StringBuffer render(RenderContext rContext) throws RenderException {
		if (elements.get("var") == null) {
			throw new RenderException("u:foreach requires a variable to iterate through.");
		}

		VariableStoreInterface vsInterface = rContext.getVariableStore().getVariable(elements.get("var"));
		StringBuffer buf = new StringBuffer();
		
		if (vsInterface.isIterative()) {
			if (vsInterface.getType() == VariableType.SQL) {
				ResultSet rSet = (ResultSet) vsInterface.getObject();
				
				try {
					if (rSet.next()) {
						buf.append(super.render(rContext));
					}
				} catch(SQLException ex) {
					debug("Unable to move to next result set.");
				}
			} else if (vsInterface.getType() == VariableType.MAP) {
			} else if (vsInterface.getType() == VariableType.ARRAY) {
				List<VariableStoreInterface> vsInterfaces = (List<VariableStoreInterface>) vsInterface.getObject();
				
				for(VariableStoreInterface vsInt : vsInterfaces) {
					rContext.getVariableStore().setVariable(elements.get("dest"), vsInt);
					buf.append(super.render(rContext));
				}
			}
		} else {
			throw new RenderException("u:foreach requires an iterative variable to traverse.");
		}
		
		return buf;
	}
}